package com.dc.project.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dc.common.annotation.DataScope;
import com.dc.common.core.MasterSlaveDto;
import com.dc.common.exception.ServiceException;
import com.dc.common.utils.PageUtil;
import com.dc.common.vo.ResultVo;
import com.dc.project.system.dao.SysUserRoleDao;
import com.dc.project.system.dto.SysUserRoleDto;
import com.dc.project.system.entity.SysRole;
import com.dc.project.system.entity.SysUserRole;
import com.dc.project.system.service.SysUserRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户角色表(SysUserRole)表服务实现类
 *
 * @author zhuangcy
 * @since 2021-06-03 16:42:33
 */
@Service("sysUserRoleService")
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleDao, SysUserRole> implements SysUserRoleService {

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return
     */
    @Override
    public ResultVo queryById(Serializable id) {
        return ResultVo.success().data(this.getById(id));
    }

    /**
     * 分页查询用户角色表
     *
     * @param dto
     * @return
     */
    @DataScope
    @Override
    public ResultVo queryByPage(SysUserRoleDto dto) {
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        IPage<SysUserRole> page = this.page(PageUtil.convert2PageParam(dto), queryWrapper);
        return ResultVo.success().data(PageUtil.convert2PageResult(page));
    }

    /**
     * 新增用户角色表
     *
     * @param sysUserRole
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo add(SysUserRole sysUserRole) {
        return ResultVo.verify(this.save(sysUserRole));
    }

    /**
     * 编辑用户角色表
     *
     * @param sysUserRole
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo edit(SysUserRole sysUserRole) {
        return ResultVo.verify(this.updateById(sysUserRole));
    }

    /**
     * 根据主键删除用户角色表
     *
     * @param id 主键
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo delete(Serializable id) {
        return ResultVo.verify(this.removeById(id));
    }

    /**
     * 批量新增用户角色表
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResultVo addRoles(MasterSlaveDto<Integer, SysUserRole> dto) {
        Integer userId = dto.getMaster();
        List<SysUserRole> list = dto.getSlaves();
        for (SysUserRole role : list) {
            role.setUserId(userId);
        }
        if (this.saveBatch(list, list.size())) {
            return ResultVo.success();
        }
        throw new ServiceException();
    }

    /**
     * 判断角色是否被使用
     *
     * @param roleId
     * @return
     */
    @Override
    public boolean existUser(Integer roleId) {
        return baseMapper.existUser(roleId) > 0;
    }

    /**
     * 新增用户关联角色
     *
     * @param userId
     * @param roleIds
     * @return
     */
    @Override
    public boolean addUserRoles(Integer userId, Integer[] roleIds) {
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId, userId);
        // 先删除
        boolean remove = this.remove(queryWrapper);
        // 再新增
        if (null != roleIds && roleIds.length != 0) {
            List<SysUserRole> userPosts = Arrays.asList(roleIds).stream().map(roleId -> {
                SysUserRole userRole = new SysUserRole();
                userRole.setUserId(userId);
                userRole.setRoleId(roleId);
                return userRole;
            }).collect(Collectors.toList());
            return this.saveBatch(userPosts, userPosts.size());
        }
        return remove;
    }

    /**
     * 根据用户id查询相关角色
     *
     * @param userId
     * @return
     */
    @Override
    public List<SysRole> getUserRoles(Integer userId) {
        return baseMapper.getUserRolesByUserId(userId);
    }
}